using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public abstract class lwEZAutoSpriteControlBase : AutoSpriteControlBase
{
	public override Vector2 GetDefaultPixelSize(PathFromGUIDDelegate guid2Path, AssetLoaderDelegate loader)
	{
		TextureAnim a = DefaultState;
		CSpriteFrame f = DefaultFrame;

		if(a == null)
			return Vector2.zero;
		if(a.framePaths == null)
			return Vector2.zero;
		if (a.framePaths.Length == 0)
			return Vector2.zero;
		if(f == null)
		{
			Debug.LogWarning("Sprite \"" + name + "\" does not seem to have been built to an atlas yet.");
			return Vector2.zero;
		}

		Vector2 size = Vector2.zero;
		
		
		Texture2D tex = null;
		if(!string.IsNullOrEmpty(a.framePaths[0]) && System.IO.File.Exists(System.IO.Path.GetFullPath(lwBuildSettings.GetSpriteRootPath() + a.framePaths[0])))
		{
			WWW image = new WWW("file://" + System.IO.Path.GetFullPath(a.framePaths[0]));
			while(!image.isDone);
			image.LoadImageIntoTexture(tex);
		}

		if(tex == null)
		{
			if(spriteMesh != null)
			{
				tex = (Texture2D)spriteMesh.material.GetTexture("_MainTex");
				size = new Vector2(f.uvs.width * tex.width, f.uvs.height * tex.height);
			}
		}
		else
			size = new Vector2(tex.width * (1f / (f.scaleFactor.x * 2f)), tex.height * (1f / (f.scaleFactor.y * 2f)));

		return size;
	}

	public override void Aggregate(PathFromGUIDDelegate guid2Path, LoadAssetDelegate load, GUIDFromPathDelegate path2Guid)
	{
		List<Texture2D> texList = new List<Texture2D>();
		List<CSpriteFrame> frameList = new List<CSpriteFrame>();

		for (int i = 0; i < States.Length; ++i)
		{
			States[i].Allocate();

			States[i].spriteFrames = new CSpriteFrame[States[i].framePaths.Length];
			for (int j = 0; j < States[i].spriteFrames.Length; ++j)
				States[i].spriteFrames[j] = new CSpriteFrame();

			for (int j = 0; j < States[i].framePaths.Length; ++j)
			{
				if (States[i].framePaths[j].Length < 1)
					continue;
				if (!string.IsNullOrEmpty(States[i].framePaths[j]) && System.IO.File.Exists(System.IO.Path.GetFullPath(lwBuildSettings.GetImagesFolder() + States[i].framePaths[j])))
				{
					WWW image = new WWW("file://" + System.IO.Path.GetFullPath(lwBuildSettings.GetImagesFolder() + States[i].framePaths[j]));
					while(!image.isDone);
					Texture2D tex = new Texture2D(image.texture.width, image.texture.height, TextureFormat.ARGB32, false);
					image.LoadImageIntoTexture(tex);
					tex.name = States[i].framePaths[j];
					texList.Add(tex);
					frameList.Add(States[i].spriteFrames[j]);
				}
				else
				{
					Debug.LogWarning("Image not found : " + System.IO.Path.GetFullPath(lwBuildSettings.GetImagesFolder() + States[i].framePaths[j]));
					texList.Add(null);
					frameList.Add(States[i].spriteFrames[j]);
				}
			}
		}
		
		sourceTextures = texList.ToArray();
		spriteFrames = frameList.ToArray();
	}
}
